package org.hiucung.orangemusic;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.LinearSmoothScroller;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.hiucung.orangemusic.adapter.MusicAdapter;
import org.hiucung.orangemusic.bean.MusicBean;
import org.hiucung.orangemusic.helper.MediaPlayerHelper;
import org.hiucung.orangemusic.utils.MusicDataUtil;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    public static final int REQUEST_CODE = 8848;//activity的响应码

    private static final String TAG = "MainActivity:";

    ImageView nextIv,playIv,prevIv,iconIv;//上一首、下一首、播放/暂停、专辑图片

    TextView singerTv,songTv;//歌手名，歌曲名

    RecyclerView musicRv;

    ArrayList<MusicBean> mDatas;//数据源

    private MusicAdapter adapter;//适配器

    int currnetPlayPosition = -1; //初始化播放状态为-1

    int currnetPausePosition;//初始化暂停状态

    LinearLayoutManager layoutManager;//设置布局管理器

    View bottomlayout;

    Bitmap albumBitmap;

    MusicBean musicBean;

    MediaPlayerHelper mediaPlayerHelper;//初始化媒体帮助类

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        initView();

        //初始化媒体帮助类，使用单例模式控制全局媒体
        mediaPlayerHelper = MediaPlayerHelper.getInstance(this);

        //加载本地数据源
        mDatas = MusicDataUtil.getMusicData(this);

        //创建适配器
        adapter = new MusicAdapter(this,mDatas);
        musicRv.setAdapter(adapter);

        //设置布局管理器
        layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        musicRv.setLayoutManager(layoutManager);

        //数据源变化，提示适配器更新
        adapter.notifyDataSetChanged();

        //设置每一项的点击事件
        setEventListener();

        //点击底部操作栏传送数据给PlayerActivity
        bottomlayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                IntentPlayerActivity();
            }
        });
    }

    //跳转到PlayerActivity
    public void IntentPlayerActivity() {
        Intent intent = new Intent(MainActivity.this,
                PlayerActivity.class);
        Bundle bundle = new Bundle();

        //防止数组超下标报错
        if (currnetPlayPosition!=-1){
            bundle.putInt("currnetPlayPosition",currnetPlayPosition);
        }else {
            currnetPlayPosition = 0;
            bundle.putInt("currnetPlayPosition",currnetPlayPosition);
        }

        //由于LocalMusicBean实现了序列化的接口，那么集合泛型的也是序列化之后的结果
        //直接发送全部音乐数据和播放位置，保证两边切歌信息显示准确
        bundle.putSerializable("mDatas",mDatas);

        intent.putExtras(bundle);
        //配置跳转动画
        startActivityForResult(intent,
                REQUEST_CODE, ActivityOptions.makeSceneTransitionAnimation(MainActivity.this).toBundle());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 当otherActivity中返回数据的时候，会响应此方法
        // requestCode和resultCode必须与请求startActivityForResult()和返回setResult()的时候传入的值一致。
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == PlayerActivity.RESULT_CODE) {
            Bundle bundle = data.getExtras();
            currnetPlayPosition = bundle.getInt("currnetPlayPosition");
            Log.i(TAG,"onActivityResult: playerActivity发出finish请求");
            updatePlayerMusicUI(mDatas.get(currnetPlayPosition));
        }
        //回调MainActivity时也需要判断显示按钮的状态
        if (mediaPlayerHelper.isPlaying()){
            playIv.setImageResource(R.mipmap.landscape_pause_icon_normal);
        }else {
            playIv.setImageResource(R.mipmap.landscape_play_icon_normal);
        }
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.local_music_bottom_iv_prev:
                if (currnetPlayPosition == 0 || currnetPlayPosition == -1) {
                    //已经是第一首
                    Toast.makeText(this,"已经是第一首音乐啊TNT",Toast.LENGTH_SHORT).show();
                    return;
                }else {
                    currnetPlayPosition = currnetPlayPosition - 1;
                    musicBean = mDatas.get(currnetPlayPosition);
                    playMusicInBean(musicBean);
                    //recycleView定位
                    ChangeRecycleViewPosition();

                    break;
                }

            case R.id.local_music_bottom_iv_play:
                if (currnetPlayPosition == -1) {
                    //并没有选中音乐，从第一首歌开始播放
                    Toast.makeText(this,"没有选中音乐啊TNT，帮你选择第一首歌",Toast.LENGTH_SHORT).show();
                    currnetPlayPosition = currnetPlayPosition + 1;
                    MusicBean nextBean = mDatas.get(currnetPlayPosition);
                    playMusicInBean(nextBean);
                    return;
                }else if (mediaPlayerHelper.isPlaying()){
                    //暂停音乐
                    pauseMusic();
                }else{
                    //从暂停位置开始播放音乐
                    playMusic();
                }
                break;

            case R.id.local_music_bottom_iv_next:
                if (currnetPlayPosition == mDatas.size()-1) {
                    //已经是第一首
                    Toast.makeText(this,"已经是最后一首音乐啊TNT",Toast.LENGTH_SHORT).show();
                }else {
                    currnetPlayPosition = currnetPlayPosition + 1;
                    musicBean = mDatas.get(currnetPlayPosition);
                    playMusicInBean(musicBean);
                    //recycleView定位
                    ChangeRecycleViewPosition();

                    break;
                }
        }
    }

    //提示layoutManager  recycleView定位
    private void ChangeRecycleViewPosition() {
        final TopSmoothScroller mScroller = new TopSmoothScroller(this);
        mScroller.setTargetPosition(currnetPlayPosition);
        layoutManager.startSmoothScroll(mScroller);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopMusic();
    }

    /***
     * 点击事件通过实现接口实现类
     */
    private void setEventListener() {
        adapter.setOnItemClickListener(new MusicAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick(View view, int position) {

                currnetPlayPosition = position;//获取点击的position
                musicBean = mDatas.get(position);//根据position获取歌曲列表中的歌曲
                playMusicInBean(musicBean);//播放该歌曲

                //TODO 需要判断是否第二次点击该歌曲，如果是，则直接跳转activity
                IntentPlayerActivity();

            }
        });
    }

    /***
     * 更新前台可视化视图，只用于前台界面状态恢复
     */
    private void updatePlayerMusicUI(MusicBean musicBean){

        //设置专辑图片到底部控制栏
        setAlbumImage(musicBean);

        //底部同步显示歌曲信息
        singerTv.setText(musicBean.getSinger());
        songTv.setText(musicBean.getSong());
    }

    /***
     * 更新可视化视图并播放下一首
     * @param musicBean
     */
    private void playMusicInBean(MusicBean musicBean) {

        //设置专辑图片到底部控制栏
        setAlbumImage(musicBean);

        //底部同步显示歌曲信息
        singerTv.setText(musicBean.getSinger());
        songTv.setText(musicBean.getSong());

        mediaPlayerHelper.setPath(musicBean.getPath());
        playMusic();
    }

    //同步设置专辑图片到底部控制栏
    private void setAlbumImage(MusicBean musicBean) {
        MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
        mediaMetadataRetriever.setDataSource(musicBean.getPath());
        byte[] picture = null;
        picture = mediaMetadataRetriever.getEmbeddedPicture();

        if (picture!=null){
            albumBitmap = BitmapFactory.decodeByteArray(picture,0,picture.length);
            iconIv.setImageBitmap(albumBitmap);
        }else {
            iconIv.setImageResource(R.mipmap.audio_player_default_show_bg);
        }
    }

    /***
     * 播放音乐按钮的方法
     */
    private void playMusic() {
        if (!mediaPlayerHelper.isPlaying()) {
            mediaPlayerHelper.setOnMeidaPlayerHelperListener(new MediaPlayerHelper.OnMeidaPlayerHelperListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mediaPlayerHelper.start();
                }

                @Override
                public void onCompletion(MediaPlayer mp) {
                    //默认单曲循环
                    mediaPlayerHelper.seekTo(0);
                    mediaPlayerHelper.start();
                }
            });
            playIv.setImageResource(R.mipmap.landscape_pause_icon_normal);
        }else {
            //当音乐暂停之后再继续播放时不需要监听是否异步加载完成
            mediaPlayerHelper.seekTo(currnetPausePosition);
            mediaPlayerHelper.start();
            playIv.setImageResource(R.mipmap.landscape_pause_icon_normal);
        }
    }

    /***
     * 暂停音乐按钮的方法
     */
    private void pauseMusic() {
        mediaPlayerHelper.pause();
        //暂停音乐把暂停位置得到
        currnetPausePosition = mediaPlayerHelper.getCurrentPosition();
        playIv.setImageResource(R.mipmap.landscape_play_icon_normal);
    }

    /**
     * 停止并结束音乐，用于销毁
     */
    private void stopMusic() {
        currnetPausePosition = 0;
        mediaPlayerHelper.pause();
        playIv.setImageResource(R.mipmap.landscape_play_icon_normal);
    }

    private void initView(){
        checkPermission();
        //初始化控件
        nextIv = findViewById(R.id.local_music_bottom_iv_next);
        playIv = findViewById(R.id.local_music_bottom_iv_play);
        prevIv = findViewById(R.id.local_music_bottom_iv_prev);
        iconIv = findViewById(R.id.local_music_bottom_iv_icon);
        singerTv = findViewById(R.id.local_music_bottom_tv_singer);
        songTv = findViewById(R.id.local_music_bottom_tv_song);
        musicRv = findViewById(R.id.local_music_rv);
        bottomlayout = findViewById(R.id.local_music_bottomlayout);

        prevIv.setOnClickListener(this);
        playIv.setOnClickListener(this);
        nextIv.setOnClickListener(this);

    }

    /**
     * 重写LinearSmoothScroller,点击下一首时，recycleView滚动到歌曲位置
     */
    public static class TopSmoothScroller extends LinearSmoothScroller {
        TopSmoothScroller(Context context) {
            super(context);
        }

        @Override
        protected int getHorizontalSnapPreference() {
            return SNAP_TO_START;
        }

        @Override
        protected int getVerticalSnapPreference() {
            return SNAP_TO_START;
        }
    }

    /**
     * 获取权限
     */
    public void checkPermission() {
        boolean isGranted = true;
        if (android.os.Build.VERSION.SDK_INT >= 23) {
            if (this.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                //如果没有写sd卡权限
                isGranted = false;
            }
            if (this.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                isGranted = false;
            }
            if (this.checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                isGranted = false;
            }
            Log.i("权限获取", " ： " + isGranted);
            if (!isGranted) {
                this.requestPermissions(
                        new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission
                                .ACCESS_FINE_LOCATION,
                                Manifest.permission.READ_EXTERNAL_STORAGE,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.RECORD_AUDIO
                        },
                        102);
            }
        }
    }
}